package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    /**
     * 用户登录
     * */
    @Override
    public User Login(UserLoginDTO dto) {

        // 1 通过httpclient，构造登录校验请求
        // 1.1 构造请求参数
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid",weChatProperties.getAppid());
        params.put("secret",weChatProperties.getSecret());
        params.put("js_code", dto.getCode());
        params.put("grant_type","authorization_code");
        // 1.2 发请求
        String res = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", params);
        // 解析响应结果，拿到openid
        log.info(res);
       JSONObject parse = JSON.parseObject(res);
        String openid = (String)parse.get("openid");
        if(openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 根据openid查询
        User user = userMapper.getByOpenid(openid);
        // 判断是否是新用户，根openid查询
        if(user==null){
            // 是新用户，创建
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            user.setName(openid.substring(0,5)); // 取前五个字符作为姓名
            userMapper.addUser(user);
        }
        // 如果不是直接返回User
        return user;
    }
}
